package com.aioz.security.service.impl;

import com.aioz.security.common.ResponseResult;
import com.aioz.security.entity.Application;
import com.aioz.security.entity.LoginUser;
import com.aioz.security.entity.Position;
import com.aioz.security.entity.Resume;
import com.aioz.security.entity.dto.ApplicationDto;
import com.aioz.security.mapper.ApplicationMapper;
import com.aioz.security.mapper.ResumeMapper;
import com.aioz.security.service.ApplicationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Aioz
 * @since 2022-09-28
 */
@Service
@Slf4j
public class ApplicationServiceImpl extends ServiceImpl<ApplicationMapper, Application> implements ApplicationService {

    private static final int PAGE_SIZE = 2;

    @Resource
    private ApplicationMapper applicationMapper;

    @Resource
    private ResumeServiceImpl resumeService;

    @Resource
    private PositionServiceImpl positionService;

    @Override
    public ResponseResult apply(Application application) {
        application.setApplyTime(LocalDateTime.now());
        //获取登录用户ID
        Long userId = getCurrentUserId();
        application.setUserId(Math.toIntExact(userId));
        Integer hrId = positionService.getById(application.getPositionId()).getHrId();
        application.setHrId(hrId);
        Integer resumeId = resumeService.query().eq("user_id", userId).one().getId();
        application.setResumeId(resumeId);
        log.info("申请信息{}",application);
        Application isApplication = query().eq("user_id", userId)
                .eq("position_id", application.getPositionId())
                .one();
        if(!Objects.isNull(isApplication)){
            return new ResponseResult<>(200,"请勿重复提交申请信息！");
        }
        applicationMapper.insert(application);
        return new ResponseResult(200,"成功提交面试申请!");
    }

    @Override
    public ResponseResult getApplicationByHr(String name) {
        List<ApplicationDto> applications = applicationMapper.queryAllApplications();
        applications = applications.stream()
                    .filter(applicationDto -> name.equals(applicationDto.getHrName()))
                    .collect(Collectors.toList());
        log.info("申请信息{}",applications);
        return new ResponseResult(200,applications);
    }

    @Override
    public ResponseResult getAllApplication() {
        List<ApplicationDto> applications = applicationMapper.queryAllApplications();
        for (ApplicationDto application : applications) {
            application.setResume(resumeService.getById(application.getResumeId()));
        }
        return new ResponseResult(200,applications);
    }

    @Override
    public ResponseResult getOwn(Integer currentPage) {
        //获取登录用户ID
        Long userId = getCurrentUserId();
        List<ApplicationDto> applications = applicationMapper.getOwnById(userId);
        applications = applications.stream().skip((currentPage - 1) * 3L).limit(3).collect(Collectors.toList());
        return new ResponseResult(200,applications);
    }

    @Override
    public ResponseResult refuseApplication(Integer applicationId) {
        log.info("ID 为 {} 的申请已拒绝",applicationId);
        boolean isSuccess = update().eq("id", applicationId).setSql("state = 0").update();
        if(!isSuccess){
            return new ResponseResult<>(200,"权限不足，请联系管理员！");
        }
        return new ResponseResult<>(200,"已拒绝该申请");
    }

    @Override
    public ResponseResult likeApplicationByUsername(String username, Integer companyId) {
        List<ApplicationDto> applications = applicationMapper.getApplicationByUsername(companyId, username);
        if(applications.size() == 0){
            return new ResponseResult<>(200,"该用户暂无提交简历!");
        }
        return new ResponseResult<>(200,applications);
    }

    @Override
    public ResponseResult getApplicationsByCompany(Integer companyId,Integer currentPage) {
        long startTime = System.currentTimeMillis();
        List<ApplicationDto> applications = applicationMapper.getApplicationByCompanyId(companyId);
        Integer size = applications.size();
        applications= applications.stream()
                    .skip((long) currentPage * PAGE_SIZE - PAGE_SIZE)
                    .limit(PAGE_SIZE)
                    .collect(Collectors.toList());
        Map<String,Object> map = new HashMap<>();
        map.put("applications",applications);
        map.put("size",size);
        long endTime = System.currentTimeMillis();
        //打印
        log.info("程序运行时间{} ms" ,(endTime - startTime));
        return new ResponseResult<>(200,map);
    }

    public Long getCurrentUserId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getId();
    }
}
